package com.example.lab04.controller;

import com.example.lab04.entity.Product;
import com.example.lab04.service.ProductService;
import com.example.lab04.util.UploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController extends BaseController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("queryAll")
    private String queryAll() {
        // todo
        return "/product";
    }

    @GetMapping("queryAllRecommended")
    @ResponseBody
    private List<Product> queryAllRecommended() {
        return productService.queryList("queryAllRecommended", null);
    }

    @PostMapping("create")
    @ResponseBody
    private boolean create(@RequestPart MultipartFile file, @RequestPart MultipartFile[] files, @RequestPart Product product) {
//        String path = "D:/lab04/product";
//        product.setPicture(UploadUtil.savePicture(file, path));
//        String[] filenames = new String[files.length];
//        for (int i = 0; i < files.length; i++) {
//            filenames[i] = "\"" + UploadUtil.savePicture(files[i], path) + "\""; //  ["1.jpg", "2.png"]
//        }//            filenames[i] = UploadUtil.savePicture(files[i], path); 以不带双引号的方式保存
//        product.setPictures(Arrays.toString(filenames));
        String directory = "D:/lab04/product";
        product.setPicture(UploadUtil.savePicture(file, directory));
        product.setPictures(UploadUtil.savePicture(file, directory));
        productService.create(product);
        return true;
    }

    @GetMapping("detail/{id}")
    private String detail(@PathVariable BigInteger id, Model model) {
        Product product = productService.queryById(id);
        product.setPictures(product.getPictures().replaceAll("[\\[\\]\"\s]", ""));
        session.setAttribute("product", product);
        model.addAttribute("product", product);
        return "/detail";
    }
}
